define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var util = require('util');
	var utilDSP = require('modules/common');

	var List = view.container.extend({
		init:function(config){
			config = pubjs.conf(config, {
				'class': 'P-adminSmartMonitorList',
				'url': {
					'start': 'campaign/start',
					'pause': 'campaign/pause',
					'remove': 'campaign/remove',
					'recover': 'campaign/recover',
					'replaceName': 'campaign/nameReplace'
				}
			});
			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			var c = self.getConfig();
			// var el = self.getDOM();

			self.append($([
				'<div class="M-formHead">',
					'<span pub-name="add" pub-mod="@base/common/drop.add" class = "ml10"></span>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="highGrid" pub-mod="monitor/grid/grid.monitorList"/>'
			].join('')));

			var config = {
				'highGrid': {
					'gridName': 'campaign',
					'hasBatch': true,
					'eventDataLoad': true,
					'hasSearch': true,
					'hasWordsSearch': true,
					'hasFilterSidebar': true,
					'subs':[
						'mediaAndAd_Monitor','sweety','whisky','period','frequency','region','client'
					],
					'sidebar_config': {
						'items': [
							{'name': 'channel', 'uri':'modules/sideBarBase.channel','config':{'filterAccess': true,'mode': 2}},
							{'name': 'plan', 'uri': 'modules/sideBarBase.qualificationRadio', 'config': {
								'title': LANG('计划：'),
								'data': [
									{id: 0, name: LANG('全部')},
									{id: 1, name: LANG('指定计划')}
								],
								'value': 0,
								'select_config': {
									url: 'plan/list',
									name: LANG('添加筛选计划'),
									grid_mod: 'campaign/modules/select.nameGrid',
									param: {
										// 'no_limit': true,
										'mongoField': ['_id', 'Name']
									},
									gridTitle: LANG('选择计划')
								}
							}},
							{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
								'title': LANG('状态：'),
								'data': [
									{id: 0, name: LANG('所有有效活动')},
									{id: 2, name: LANG('进行中')},
									{id: 4, name: LANG('已暂停')},
									{id: 3, name: LANG('已结束')},
									{id: 1, name: LANG('未开始')},
									{id: 5, name: LANG('超预算')},
									{id: 6, name: LANG('草稿')},
									{id: 7, name: LANG('已归档')}
								],
								'value': 0
							}},
							{'name': 'label', 'uri':'modules/sideBarBase.label', 'config': {
								url: 'campaign/labels'
							}},
							{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
								'metrics': ["{front}","{back}","{conversion}","{cost}"]
							}}
						]
					}
				},
				'add':{
					'def': LANG('新建监测'),
					'href': '#serving/monitorEdit',
					'href_target': '_self'
				},
				'date': {
					'pos': 'bR'
				}
			};

			self.buildFromTemplate(config);

		},
		afterBuildTemplate: function(){
		},
		// 操作列点击事件
		onOperateMenuShow: function(ev) {
			var data = ev.param;
			var status = data.Status;
			var returnList = [];

			if(!data.IsGranted){
				if(pubjs.checkRight('monitor.updateAlarmStatus')){
					//1 启动  0暂停
					switch (status){
						case 2:
							returnList.push({'id': 'start','name': LANG('开启')});
							break;
						case 1:
							returnList.push({'id': 'pause','name': LANG('暂停')});
							break;
					}
				}
				if(pubjs.checkRight('monitor.deleteAlarm')){
					returnList.push({'id': 'remove','name': LANG('删除')});
				}
			}


			if(data.IsGranted){
				if(pubjs.checkRight('monitor.infoAlarm')){
					returnList.push({
						'id': 'check',
						'name': LANG('查看')
					});
				}
			}
			else{
				if(pubjs.checkRight('monitor.updateAlarm')){
					returnList.push({
						'id': 'edit',
						'name': LANG('编辑')
					});
				}
			}

			// 归档状态下，还原操作
			if(data.IsDeleted){
				if(pubjs.checkRight('monitor.restoreAlarm')){
					returnList.push({
						'id':'restore',
						'name':LANG('还原')
					});
				}
				ev.returnValue = returnList;
				return false;
			}

			if(!data.IsGranted){
				if(pubjs.checkRight('monitor.grant')){
					returnList.push({
						'id':'auth',
						'name':LANG('检测诊断')
					});
				}
			}

			if(pubjs.checkRight('monitor.updateAlarm')){
				returnList.push({
					'id': 'saveas',
					'name': LANG('另存为')
				});
			}

			ev.returnValue = returnList;
			return false;
		},
		// 操作列选项点击事件
		onOperateMenuSelect: function(ev) {
			var self = this;
			var key = ev.param[0]['key'];
			var selected = ev.param[1];
			var id = +selected['_id'];

			switch (key){
				case 'check':
					// window.open('#admin/smartMonitor/check/' + id);
					break;
				case 'edit':
					window.open('#serving/monitorEdit/' + id,"_self");
					break;
				case 'saveas':
					window.open('#serving/monitorSaveas/' + id,"_self");
					break;
				case 'start':
				case 'pause':
					self.toggleStatus(id, key);
					break;
				case 'remove':
					self.remove(id, selected);
					break;
				case 'restore':
					self.restore(id, selected);
					break;
			}
		},
		//
		onBatchShow: function(ev){
			var list = [];
			var batch = [
				{id: 'set', name: LANG('设置'), right: '',
					subs:[
						{id: 'replaceName', name: LANG('监测名称关键字替换'), right: ''}
					]
				},
				{id: 'pause', name: LANG('暂停'), right: ''},
				{id: 'start', name: LANG('开始'), right: ''},
				{id: 'remove', name: LANG('归档'), right: ''},
				{id: 'recover', name: LANG('还原'), right: ''},
				{id: 'export', name: LANG('导出'), right: ''}
			];

			// 检查权限
			util.each(batch, function(item){
				if(!item.right || pubjs.checkRight(item.right))
				{
					list.push(item);
				}
			});

			ev.returnValue = list;
			return false;
		},
		// 批量操作-响应菜单操作
		onBatchSelect: function(ev){
			var c = this.getConfig();
			var data = ev.param[0];
			var ids = ev.param[1];
			var contents = ev.param[2];
			var key = data.key || '';

			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择监测'));
				return false;
			}

			// 设置子菜单的部分内容编辑,id是用点分割
			var keys = key.split('.');
			if (keys.shift() === 'batchEdit') {
				this.$.batchEdit.reset().show().setTitle(data.name).setType(keys.shift()).setParam(ids);
				return false;
			}
			var self = this;
			switch(key){
				case 'start':
					pubjs.mc.send(c.url.start,{'id': ids }, self.onBatchEditSuccess.bind(self));
					break;
				case 'pause':
					pubjs.mc.send(c.url.pause,{'id': ids }, self.onBatchEditSuccess.bind(self));
					break;
				case 'remove':
					pubjs.mc.send(c.url.remove,{'id': ids }, self.onBatchEditSuccess.bind(self));
					break;
				case 'recover':
					pubjs.mc.send(c.url.recover,{'id': ids }, self.onBatchEditSuccess.bind(self));
					break;
				case 'replaceName':
					this.showReplacePopwin();
					break;
				case 'export':
					var url = utilDSP.getExportApi(this.get('highGrid'), ids);
					window.location.href = url;
					break;
			}

			return false;
		},
		onBatchEditSuccess: function(err,data){
			this.$.highGrid.reload();
			return false;
		},
		showReplacePopwin: function(){
			if(this.$.replaceNamePopwin){
				this.$.replaceNamePopwin.show();
			}
			else{
				this.createAsync('replaceNamePopwin','whisky/popwin/nameReplace.base',{
					"layout": {
						"module": '@base/dialog.base'
						,"mask":1
						,"title": LANG('广告监测名称关键词替换')
						,'silence': false
						,"width": 500
					}
				},function(mod,created){
					if(created){
						mod.reset().show();
					}
					else{
						mod.show();
					}
				})
			}
		},
		onNameReplace: function(data){
			var c = this.getConfig();
			var self = this;
			var param = {};
			param.ids = this.$.highGrid.getSelectRowIds();
			param.newKeyword = data.param.data.newKeyword;
			param.originalKeyword = data.param.data.originalKeyword;

			pubjs.mc.send(c.url.replaceName,param,function(err,data){
				if(err){
					pubjs.error(err.message);
					pubjs.alert(err.message);
					return false;
				}
				pubjs.alert(data.message);
				self.$.highGrid.load();
			});
			return false;
		},
		//响应右边侧边栏选项
		onSidebarFilter: function(ev){
			var self = this
				,param = {};
			util.each(ev.param, function(item, idx){
				var type = idx;
				var id = item.id;
				switch (type) {
					case 'channel':
						param.SubChannel = +id;
						break;
					case 'status':
						param.Status = +id;
						break;
					case 'plan':
						var plan = ev.param.plan;
						param.PlanId = plan.data;
						break;
					case 'label':
						var label = ev.param.label;
						if(label.id && label.id.length){
							param.Label = label.id.split(",");
						}
						else{
							param.Label = [];
						}
						break;
					case 'metrics':
						param.metrics_filter = id;
						break;
				}
			});
			self.$.highGrid.reload(param);
		},
		//禁止和启动操作
		toggleStatus: function(id, key){
			var self = this;
			var c = this.getConfig();
			var statusText = '';
			var status = 2;
			var url = null;
			switch (key){
				case 'start':
					statusText = LANG('开启');
					status = 1;
					url = c.url.start;
					break;
				case 'pause':
					statusText = LANG('暂停');
					status = 2;
					url = c.url.pause;
					break;
			}

			pubjs.confirm(LANG('%1该广告监测？', statusText),
				function(isOk){
					pubjs.mc.send(url, {
						'id': id,
						'Status': status
					},
						self.onToggleStatus.bind(self)
					);
				}
			);
		},
		onToggleStatus: function(){
			// pubjs.alert('修改成功');
			this.reload();
			return false;
		},
		//删除操作
		remove: function(id, data){
			if(!id){
				return false;
			}
			var self = this;
			var c = this.getConfig();
			pubjs.confirm(LANG('是否确认删除？'),function(isOk){
				if(isOk){
					pubjs.mc.send(c.url.remove,{'id': id},
						self.onRemove.bind(self)
					);
				}
			});
		},
		onRemove: function( err, data ) {
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			this.reload();
		},
		restore: function(id, data){
			if(!id){
				return false;
			}
			var self = this;
			var c = this.getConfig();
			pubjs.confirm(LANG('是否确认还原该广告监测？'),function(isOk){
				if(isOk){
					pubjs.mc.send(c.url.recover,{'id': id},
						self.onRemove.bind(self)
					);
				}
			});
		},
		reload: function(param) {
			this.$.highGrid.reload(param);
		},
		onAddAuthSuccess: function(){
			this.reload();
		},
		// 避免计划筛选完成，筛选拦隐藏的问题
		onMainPopwinOk: function(){
			this.$.highGrid.showPanel();
			return false;
		},
	});
	exports.list = List;
});